08. Exercises
Exercises
Now it's your turn to write C++ programs.
Practicing is the best way to improve your C++ skills. Here you will find a few ideas to get you started. We have not provided a code playground this time, so you will need to compile and execute programs locally on your computer.
These are non-graded, so it's up to you how many you want to complete. At the end of the C++ Basics Module, there will be a more comprehensive project asking you to translate Python code to C++.
If you get stuck because you are not sure how to code something or how to decipher an error, use a search engine like Google or Bing. You can copy and paste an error message directly and oftentimes, somebody has already written a clear explanation of what the error means and how to get rid of it.
Exercise 1
In the robot localization lectures, Sebastian Thrun led you through Python code for one-dimensional robot sensing and robot movement. You ended up with a sense() function for updating probabilities based on a sensor measurement. You also had a move() function that updated probabilities based on robot movement across a grid.
Translate the following code from Python into C++:
p = [0.2, 0.2, 0.2, 0.2, 0.2]
world = ['green', 'red', 'red', 'green', 'green']
measurements = ['red', 'green']
motions = [1,1]
pHit = 0.6
pMiss = 0.2
pExact = 0.8
pOvershoot = 0.1
pUndershoot = 0.1
def sense(p, Z):
q=[]
for i in range(len(p)):
hit = (Z == world[i])
q.append(p[i] * (hit * pHit + (1-hit) * pMiss))
s = sum(q)
for i in range(len(q)):
q[i] = q[i] / s
return q
def move(p, U):
q = []
for i in range(len(p)):
s = pExact * p[(i-U) % len(p)]
s = s + pOvershoot * p[(i-U-1) % len(p)]
s = s + pUndershoot * p[(i-U+1) % len(p)]
q.append(s)
return q
for k in range(len(measurements)):
p = sense(p, measurements[k])
p = move(p, motions[k])
print p
You can find one potential solution to the above translation here.
The expected output is:
0.211579 0.151579 0.0810526 0.168421 0.387368
Exercise 2
Write a C++ function that takes in two matrices and outputs their product. Your function should first check that the two matrices can actually be multiplied together; if matrix one is m by n and matrix two is w by z, then n must equal w. And the resulting matrix will be m by z.